package com.xw.musicplayer.focus;

import android.content.Context;
import android.media.AudioAttributes;
import android.media.AudioFocusRequest;
import android.media.AudioManager;
import android.os.Build;

import androidx.annotation.RequiresApi;

/**
 * Api26焦点管理.
 *
 * @author ingxin
 * @date 2020/5/24
 */
@RequiresApi(api = Build.VERSION_CODES.O)
public class BaseAudioFocusHelper26 extends BaseAudioFocusHelper {

    private AudioManager mAudioManager;
    private AudioFocusRequest mAudioFocusRequest;

    public BaseAudioFocusHelper26(AudioManager.OnAudioFocusChangeListener listener) {
        super(listener);
    }

    @Override
    public void request(Context context) {
        if (mAudioManager == null) {
            mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        }

        if (mAudioFocusRequest == null) {
            AudioAttributes audioAttributes = new AudioAttributes.Builder()
                    .setUsage(AudioAttributes.USAGE_MEDIA)
                    .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                    .build();
            mAudioFocusRequest = new AudioFocusRequest
                    .Builder(AudioManager.AUDIOFOCUS_GAIN)
                    .setAudioAttributes(audioAttributes)
                    //可异步获取焦点
                    .setAcceptsDelayedFocusGain(true)
                    .setOnAudioFocusChangeListener(mFocusChangeListener)
                    .build();
        }

        if (mAudioManager != null) {
            //忽略请求结果
            mAudioManager.requestAudioFocus(mAudioFocusRequest);
        }
    }

    @Override
    public void abandon() {
        if (mAudioFocusRequest != null && mAudioManager != null) {
            mAudioManager.abandonAudioFocusRequest(mAudioFocusRequest);
        }
    }

}
